<?php


namespace app\partneradmin\controller;


use app\partneradmin\model\AccountTransferLog;
use app\partneradmin\model\AppBase;
use app\partneradmin\model\CustomerServiceGroup;
use app\partneradmin\model\Partner;
use app\common\controller\partneradmin\Base;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\partneradmin\model\CustomerServiceAccountMiddle;
use app\partneradmin\model\CustomerServicePersonnel;

class Customerserviceaccount extends Base
{

    protected $noNeedLogin = [];

    protected $model;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\partneradmin\model\CustomerServiceAccount();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        if ($this->request->isPost()) {
            $page = $this->request->post('page', 1);
            $size = $this->request->post('page_size', 10);
            $sort = $this->request->post('sort', 'id');
            $order = $this->request->post('order', 'desc');
            $partnerId = $this->admin['partner_id'];
            $customerServiceGroupId = $this->request->post('customer_service_group_id', '');
            $customerServicePersonnelId = $this->request->post('customer_service_personnel_id', '');
            $username = $this->request->post('username', '');
            $where['partner_id'] = $partnerId;
            $adminCustomerServiceInfo = $this->getCustomerServiceInfo();
            switch ($this->admin['rule']) {
                case 1:
                    $customerServiceGroupId = $adminCustomerServiceInfo['customer_service_personnel_info']['customer_service_group_id'];
                    break;
                case 2:
                    $customerServicePersonnelId = $adminCustomerServiceInfo['customer_service_personnel_info']['id'];
                    break;
            }
            if ($customerServicePersonnelId != '') {
                $where['customer_service_personnel_id'] = $customerServicePersonnelId;
            }
            if ($customerServiceGroupId != '') {
                $where['customer_service_group_id'] = $customerServiceGroupId;
            }
            if ($username != '') {
                $where['username'] = ['like', '%' . $username . '%'];
            }
            $where['is_del'] = 0;
            $list = $this->model
                ->field('*')
                ->where($where)
                ->page($page, $size)
                ->order($sort, $order)
                ->select()
                ->toArray();
            if (!empty($list)) {
                //获取合作方id
                $partnerIds = array_column($list, 'partner_id');
                //去重
                $partnerIds = array_keys(array_flip($partnerIds));
                //获取客服组id
                $customerServiceGroupIds = array_column($list, 'customer_service_group_id');
                $customerServiceGroupIds = array_keys(array_flip($customerServiceGroupIds));
                //获取客服人员ids
                $customerServicePersonnelIds = array_column($list, 'customer_service_personnel_id');
                $customerServicePersonnelIds = array_keys(array_flip($customerServicePersonnelIds));
                //获取所有合作方
                $partner = new Partner();
                $partnerList = $partner->getPartnerAll(['id' => ['in', $partnerIds]], 'id,name');
                $partnerList = array_column($partnerList, null, 'id');
                //根据条件获取所有客服组
                $customerServiceGroup = new CustomerServiceGroup();
                $customerServiceGroupList = $customerServiceGroup->getCustomerServiceGroupAll(['id' => ['in', $customerServiceGroupIds]], 'id,name');
                $customerServiceGroupList = array_column($customerServiceGroupList, null, 'id');
                //根据条件获取客服人员
                $customerServicePersonnel = new \app\admin\model\CustomerServicePersonnel();
                $customerServicePersonnelList = $customerServicePersonnel->getCustomerServicePersonnelAll(['id' => ['in', $customerServicePersonnelIds]], 'id,name');
                $customerServicePersonnelList = array_column($customerServicePersonnelList, null, 'id');
                //取出所有应用列表
                $appBaseList = AppBase::select()->toArray();
                $appBaseList = array_column($appBaseList, null, 'id');
                //字段映射
                foreach ($list as $key => $value) {
                    $value['app_base_title'] = empty($appBaseList[$value['app_base_id']]) ? '' : $appBaseList[$value['app_base_id']]['title'];
                    $value['partner_name'] = empty($partnerList[$value['partner_id']]) ? '' : $partnerList[$value['partner_id']]['name'];
                    $value['customer_service_group_name'] = empty($customerServiceGroupList[$value['customer_service_group_id']]) ? '' : $customerServiceGroupList[$value['customer_service_group_id']]['name'];
                    $value['customer_service_personnel_name'] = empty($customerServicePersonnelList[$value['customer_service_personnel_id']]) ? '' : $customerServicePersonnelList[$value['customer_service_personnel_id']]['name'];
                    $list[$key] = $value;
                }
            }
            $total = $this->model->where($where)->count('id');
            $totalPage = ceil($total / $size);
            $data = [
                'total' => $total,
                'list' => $list,
                'totalPage' => $totalPage
            ];
            $this->success('列表', '', $data);
        }
    }

    /**
     * 重写新增方法
     */
//    public function add()
//    {
//        $this->error('添加失败');
////        if ($this->request->isPost()) {
////            $params = $this->request->post("");
////            if ($params) {
////                $params = $this->preExcludeFields($params);
////                $result = false;
////                Db::startTrans();
////                try {
////                    //是否采用模型验证
////                    if ($this->modelValidate) {
////                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
////                        $validate = $name . '.add';
////                        $this->model->validateFailException(true)->validate($validate);
////                    }
////                    $params['admin_id'] = $this->admin['id'];
////                    //验证合客服账号唯一性
////                    $info = $this->model->where(['username' => $params['username']])->find();
////                    if (!empty($info)) {
////                        $this->error('添加失败,客服账号已存在');
////                    }
////                    $customerServicePersonnel = new CustomerServicePersonnel();
////                    $personnelInfo = $customerServicePersonnel->get($params['customer_service_personnel_id']);
////                    if (empty($personnelInfo)) {
////                        $this->error('添加失败,找不到该客服人员');
////                    }
////                    $where = [
////                        'switch' => 1,
////                        'status' => 1,
////                        'customer_service_group_id' => $params['customer_service_personnel_id']
////                    ];
////                    $info = $this->model->where($where)->find();
////                    if (empty($info)) {
////                        $params['switch'] = 1;
////                        $params['status'] = 1;
////                    }
////                    $params['customer_service_group_id'] = $personnelInfo['customer_service_group_id'];
////                    $params['partner_id'] = $personnelInfo['partner_id'];
////                    $result = $this->model->allowField(true)->save($params);
////                    Db::commit();
////                } catch (ValidateException $e) {
////                    Db::rollback();
////                    $this->error($e->getMessage());
////                } catch (PDOException $e) {
////                    Db::rollback();
////                    $this->error($e->getMessage());
////                } catch (Exception $e) {
////                    Db::rollback();
////                    $this->error($e->getMessage());
////                }
////                if ($result !== false) {
////                    $this->success('添加成功');
////                } else {
////                    $this->error('添加失败');
////                }
////            }
////            $this->error('参数不能为空！');
////        }
//    }

    /**
     * 编辑
     */
//    public function edit($ids = null)
//    {
//        $row = $this->model->get($ids);
//        if (!$row) {
//            $this->error('不存在的数据', '', [], 404);
//        }
//        if ($this->request->isPost()) {
//            $params = $this->request->post("");
//            if ($params) {
//                $params = $this->preExcludeFields($params);
//                $result = false;
//                Db::startTrans();
//                try {
//                    //是否采用模型验证
//                    if ($this->modelValidate) {
//                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
//                        $validate = $name . '.edit';
//                        $row->validateFailException(true)->validate($validate);
//                    }
//                    //验证合客服账号唯一性
//                    $info = $this->model->where(['username' => $params['username']])->where(['id' => ['neq', $ids]])->find();
//                    if (!empty($info)) {
//                        $this->error('更新失败,客服账号已存在');
//                    }
//                    $params['admin_id'] = $this->admin['id'];
//                    $result = $row->allowField(true)->isUpdate(true)->save($params);
//                    Db::commit();
//                } catch (ValidateException $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                } catch (PDOException $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                } catch (Exception $e) {
//                    Db::rollback();
//                    $this->error($e->getMessage());
//                }
//                if ($result !== false) {
//                    $this->success('修改成功');
//                } else {
//                    $this->error('修改失败');
//                }
//            }
//            $this->error('参数不能为空！');
//        }
//    }

    /*
     * 账号转移 TODO 合作方禁止转移
     */
//    public function accountTransfer($old_username, $new_username)
//    {
//        $oldInfo = $this->model->where('username', '=', $old_username)->find();
//        if ($old_username == $new_username) {
//            $this->error('新旧账号不能是同一个！', '', null, 404);
//        }
//        if (empty($oldInfo)) {
//            $this->error('未查询到旧客服账号数据！', '', null, 404);
//        }
//        $newInfo = $this->model->where('username', '=', $new_username)->find();
//        if (empty($newInfo)) {
//            $this->error('未查询到新客服账号数据！', '', null, 404);
//        }
//        if ($oldInfo['customer_service_personnel_id'] !== $newInfo['customer_service_personnel_id']) {
//            $this->error('新旧账号所属人员不一致！');
//        }
//        //进行中间表内容转移
//        $customerServiceAccountMiddle = new CustomerServiceAccountMiddle();
//        $csaOld = $customerServiceAccountMiddle->where('customer_service_account_id', '=', $oldInfo['id'])->find();
//        if (empty($csaOld)) {
//            $this->error('旧账号下无数据转移！');
//        }
//        $updateData = [
//            'customer_service_account_id' => $newInfo['id']
//        ];
//        $where = [
//            'id' => $csaOld['id']
//        ];
//        $customerServiceAccountMiddle->update($updateData, $where);
//        $setLogData = [
//            'new_account' => $new_username,
//            'old_account' => $old_username
//        ];
//        AccountTransferLog::create($setLogData);
//        //转移成功后 所有用户的提示横幅字段打开
//        \app\admin\model\User::update(['is_show_contact_kf' => 1], ['customer_service_account_middle_id' => $csaOld['id']]);
//        $this->success('操作成功');
//    }

    /**
     * 数据的设置操作, 目前有  开关  是否默认  状态(重写)
     */
    public function setup($ids = "")
    {
        $type = $this->request->post("type");
        $val = $this->request->post("val");
        $row = $this->model->get($ids);
        if (empty($row)) {
            $this->error('未查询到数据！', '', [], 404);
        }
        $field = $type;
        switch ($type) {
            case 'switch':
                if ($val == 1) {
                    if ($row['status'] == 0) {
                        $this->error('账号未启用,请启用后操作！', '', null, 404);
                    }
                    //逻辑处理  TODO 多账号逻辑处理(每个账号都添加中间表)
                    $customerServiceAccountMiddle = new CustomerServiceAccountMiddle();
                    $setData = [
                        'customer_service_account_id' => $ids
                    ];
                    $customerServiceAccountMiddle->save($setData);
//                    $customerServiceAccountMiddle = new CustomerServiceAccountMiddle();
//                    //查询当前默认的客服是否有中间表内容未转移
//                    $infoWhere = [
//                        'customer_service_personnel_id' => $row['customer_service_personnel_id'],
//                        'switch' => 1
//                    ];
//                    $info = $this->model->where($infoWhere)->find();
//                    //如果未空代表第一次设为默认自动生成一个中间表数据
//                    if (empty($info)) {
//                        $setData = [
//                            'customer_service_account_id' => $ids
//                        ];
//                        $customerServiceAccountMiddle->save($setData);
//                    } else {
//                        //不为空则查询默认账号下是否有未转移的中间表数据
//                        $csaInfo = $customerServiceAccountMiddle->where('customer_service_account_id', '=', $info['id'])->find();
//                        if (!empty($csaInfo)) {
//                            $isTransfer = $this->checkTransfer($ids, $csaInfo['id']);
//                            if (!$isTransfer) {
//                                $this->error('账号下有未转移数据,请转移后操作！', '', [], 404);
//                            }
//                        }
//                    }
//                    $oldwhere['id'] = ['neq', $ids];
//                    $oldwhere['customer_service_personnel_id'] = $row['customer_service_personnel_id'];
//                    $oldwhere['switch'] = 1;
//                    $oldwhere['app_base_id'] = $row['app_base_id'];
//                    $this->model->update(['switch' => 0], $oldwhere);
                    $data[$field] = $val;
                    $where['id'] = $ids;
                } else {
                    $this->error('操作不可执行，客服人员下不可无启用账号');
                }
                break;
            case 'status':
                if ($val == 0) {
                    //逻辑处理
                    if ($row['switch'] == 1) {
                        $this->error('操作不可执行，不可禁用使用中的账号!');
                    }
                }
                $data[$field] = $val;
                $where['id'] = ['in', $ids];
                break;
            default:
                $this->error('不存在的业务');
                break;
        }

        $this->model->update($data, $where);
        $this->success('操作成功');
    }

    //判断账号下是否有用户无用户则直接转移
    public function checkTransfer($newId, $customer_service_account_middle_id)
    {
        $userCount = \app\admin\model\User::where([
            'customer_service_account_middle_id' => $customer_service_account_middle_id
        ])->count('id');
        //如果确实有为转移用户 则返回false
        if ($userCount > 0) {
            return false;
        }
        //为0 则直接转移
        $updateData = [
            'customer_service_account_id' => $newId
        ];
        $where = [
            'id' => $customer_service_account_middle_id
        ];
        //进行中间表内容转移
        $customerServiceAccountMiddle = new CustomerServiceAccountMiddle();
        $customerServiceAccountMiddle->update($updateData, $where);
        return true;
    }

    /**
     * 禁止新增
     */
    public function add()
    {
        $this->error('添加失败！该模块不允许添加');
    }
    /**
     * 禁止编辑
     */
    public function edit($ids = null)
    {
        $this->error('修改失败！该模块合作方不允许编辑');
    }
    /**
     * 禁止删除
     */
    public function del($ids = null)
    {
        $this->error('该模块合作方不允许操作');
    }
}